﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Security;
using System.Web;
using System.Linq;
using ChgDoc.Entity;
using System.Xml.Serialization;

namespace ChgDoc
{
	[Serializable]
    public class Visitor
    {
        private List<string> _permissions;

        public bool Has( string permission )
        {
            return HasPermission( permission );
        }

		public static bool HasPermission( string permissionCode )
        {
            if (string.IsNullOrWhiteSpace( permissionCode ))
                return true;
            
            Visitor current = Current;
            if (current.Account.IsAnonymous)
                return false;

            if (current._permissions == null)
                current._permissions = (from p in Permission.ForAccount(current.Account.Id) select p.Code).ToList();

            return current._permissions.Contains(permissionCode);
        }

        public static long AccountId { get { return Current.Account.Id; } }
        public static bool IsAnonymous { get { return Current.Account.IsAnonymous; } }
        public static string DisplayName { get { return Current.Account.DisplayName; } }

        [XmlIgnore]
        private Account _account;

        [XmlIgnore]
        private Account Account
        {
            get { return (_account ?? (_account = Account.Anonymous));  }
            set { _account = value; }
        }

        [XmlIgnore]
        public static Visitor Current 
		{
			get 
			{
                if (HttpContext.Current.Session == null)
                    return new Visitor();

                Visitor current = HttpContext.Current.Session["Visitor"] as Visitor;
				if (current == null)
				{
					current = new Visitor();
					HttpContext.Current.Session[ "Visitor" ] = current;
				}

				return current;
			}
		}
        		
        
        public static void SetAccount( Entity.Account acc )
        {
            Current._permissions = null;
            Current.Account = acc;
        }
    }
}
